﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Linq;
using DeployHelper.Logic;
using log4net;

namespace DeployHelper.View.Forms
{
	public partial class MainForm : Form
	{
		public static readonly ILog logger = LogManager.GetLogger(typeof (MainForm));
		public static TextBox DebugTextBox;

		private XDocument document;

		public MainForm(XDocument doc)
		{
			this.document = doc;

			DebugTextBox = new TextBox {
			                           	Location = new Point(13, 173),
			                           	Multiline = true,
			                           	Name = "DebugTextBox",
			                           	Size = new Size(259, 130),
			                           	TabIndex = 3,
			                           	AutoSize = true,
			                           	ScrollBars = ScrollBars.Both,
			                           	Dock = DockStyle.Fill
			                           };

			this.InitializeComponent();

			Controls.Add(DebugTextBox);

			this.tableLayoutPanel1.Controls.Add(DebugTextBox, 0, 3);
			

			var taskNames = from element in this.document.Element("tasks").Elements("task")
			                select element.Attribute("name").Value;

			this.taskListBox.DataSource = taskNames.ToList();

			this.Resize += this.MainForm_Minimize;
		}

		private void MainForm_Minimize(object sender, EventArgs e)
		{
			if (this.WindowState == FormWindowState.Minimized) {
				this.ShowInTaskbar = false;
			} else {
				this.ShowInTaskbar = true;
			}
		}


		private void executeButton_Click(
			object sender,
			EventArgs e)
		{
			var selectedTasks = this.taskListBox.SelectedItems;
			this.progressBar1.Value = 0;
			this.progressBar1.Minimum = 0;
			this.progressBar1.Maximum = selectedTasks.Count;
			this.progressBar1.Step = 1;
			
			TaskProcessor tp = new TaskProcessor(this.document);
			tp.TaskFinished += this.tp_TaskFinished;

			tp.Execute(Enumerable.Cast<string>(selectedTasks));
		}

		void tp_TaskFinished(object sender, EventArgs args)
		{
			this.progressBar1.PerformStep();
		}

		private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
		{
			this.WindowState = FormWindowState.Normal;
			this.ShowInTaskbar = true;
			this.Show();
			this.Focus();
			this.Activate();
			
		}
	}
}